from 数据库操作.CreateMysqlCon import CreateMysqlCon
from 数据库操作.LoginMysql import LoginMysql
from 工具包utils.str_operation import get_user_object

class UserOperation:
    def __init__(self):
        self.con = CreateMysqlCon().get_con()
        if not self.con:
            raise ConnectionError("数据库连接失败，请检查配置或网络")
        self.cursor = self.con.cursor()
    
    def get_all_users(self):
        """获取所有用户信息"""
        try:
            sql = "SELECT ID, username, age, gender FROM user_data ORDER BY ID"
            self.cursor.execute(sql)
            result = self.cursor.fetchall()
            return result
        except Exception as e:
            print(f"获取所有用户信息失败: {e}")
            return []
    
    def get_user_by_id(self, user_id):
        """根据ID获取用户信息"""
        try:
            sql = "SELECT * FROM user_data WHERE ID = %s"
            self.cursor.execute(sql, (user_id,))
            result = self.cursor.fetchone()
            if result:
                return get_user_object(result)
            return None
        except Exception as e:
            print(f"获取用户信息失败: {e}")
            return None
    
    def get_user_by_username(self, username):
        """根据用户名获取用户信息"""
        try:
            sql = "SELECT * FROM user_data WHERE username = %s"
            self.cursor.execute(sql, (username,))
            result = self.cursor.fetchone()
            if result:
                return get_user_object(result)
            return None
        except Exception as e:
            print(f"获取用户信息失败: {e}")
            return None
    
    def update_user_info(self, user_id, age=None, gender=None):
        """更新用户信息"""
        try:
            # 构建更新语句
            update_fields = []
            params = []
            
            if age is not None:
                update_fields.append("age = %s")
                params.append(int(age))
            
            if gender is not None:
                update_fields.append("gender = %s")
                # 转换性别为数字
                if isinstance(gender, str):
                    if gender == '男':
                        gender = 0
                    elif gender == '女':
                        gender = 1
                params.append(gender)
            
            if not update_fields:
                return False  # 没有要更新的字段
            
            # 构建SQL语句
            sql = f"UPDATE user_data SET {', '.join(update_fields)} WHERE ID = %s"
            params.append(user_id)
            
            # 执行更新
            self.cursor.execute(sql, params)
            self.con.commit()
            return True
        except Exception as e:
            print(f"更新用户信息失败: {e}")
            self.con.rollback()
            return False
    
    def delete_user(self, user_id):
        """删除用户（管理员功能）"""
        try:
            # 首先检查是否是最后一个用户，如果是则不允许删除
            self.cursor.execute("SELECT COUNT(*) FROM user_data")
            count = self.cursor.fetchone()[0]
            if count <= 1:
                return False, "系统至少需要保留一个用户"
            
            # 删除用户相关的所有数据
            # 1. 删除用户的博客评论
            self.cursor.execute("DELETE FROM comments WHERE user_id = %s", (user_id,))
            
            # 2. 删除用户的关注关系
            self.cursor.execute("DELETE FROM user_follows WHERE follower_id = %s OR followed_id = %s", 
                               (user_id, user_id))
            
            # 3. 删除用户的博客
            self.cursor.execute("DELETE FROM blog_list WHERE user_id = %s", (user_id,))
            
            # 4. 最后删除用户本身
            self.cursor.execute("DELETE FROM user_data WHERE ID = %s", (user_id,))
            
            self.con.commit()
            return True, "用户删除成功"
        except Exception as e:
            print(f"删除用户失败: {e}")
            self.con.rollback()
            return False, f"删除用户失败: {e}"